<?php
namespace App\GraphQL\Mutations\User;

use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Models\Group;
use App\Models\Device;
use Illuminate\Support\Facades\DB;

class Update
{

    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        DB::transaction(function () use ($args) {
            $data = $args['input'];
            $user = $this->validate($args['id'], $data);
            if ($data['password']) {
                $data['password'] = bcrypt($data['password']);
            } else {
                unset($data['password']);
            }
            $item = [
                'province' => '',
                'city' => '',
                'area' => ''
            ];
            if ($data['address']) {
                $tmp = explode(',', $data['address']);
                $data['province'] = $tmp[0];
                $data['city'] = $tmp[1];
                $data['area'] = $tmp[2];
                $item['province'] = $tmp[0];
                $item['city'] = $tmp[1];
                $item['area'] = $tmp[2];
            }
            $user->update($data);
            // /更新代理商设备组 设备的地理位置信息
            $groupIDs = Group::where('cate', 'DEVICE')->where('user_id', $user->id)->pluck('id');
            if ($groupIDs->count() > 0) {
                Device::whereIn('device_group_id', $groupIDs->toArray())->update($item);
            }
        });

        return [
            'status' => '200',
            'message' => '更新成功'
        ];
    }

    public function validate($id, $data)
    {
        $authUser = auth()->user();
        $roles = [];
        if ($authUser->role_code == 'ADMIN') {
            $roles = [
                'ADMIN',
                'AGENT',
                'DISTRIBUTOR',
                'MERCHANT',
                'STAFF',
                'REPAIRER'
            ];
        } else if ($authUser->role_code == 'AGENT') {
            $roles = [
                'DISTRIBUTOR',
                'MERCHANT'
            ];
        } else if ($authUser->role_code == 'MERCHANT') {
            $roles = [
                'STAFF'
            ];
        }
        $rules = [
            'name' => [
                'required',
                'max:18'
            ],
            'phone' => [
                'required',
                'min:11',
                'max:11'
            ],
            'id_card' => [
                'required'
            ],
            'role_code' => [
                'required',
                Rule::in($roles)
            ]
        ];
        $messages = [
            'name.required' => '姓名不能为空',
            'name.max' => '姓名不能超过18个字',
            'phone.required' => '手机号不能为空',
            'phone.min' => '手机号为11位',
            'phone.max' => '手机号为11位',
            'id_card.required' => '身份证不能为空',
            'role_code.required' => '角色不能为空',
            'role_code.in' => '角色不能超出限制'
        ];
        $validate = Validator::make($data, $rules, $messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
        // 验证用户是否存在
        $old = User::find($id);
        if (! $old) {
            throw new \Exception('用户不存在!');
        }

        // 判断当前手机号是否被使用
        $phoneOld = User::where('phone', $data['phone'])->first();
        if ($phoneOld && $old->id !== $phoneOld->id) {
            throw new \Exception('手机号已经被使用!');
        }
        return $old;
    }
}
